package ctrs.controller;

import com.alibaba.fastjson.JSON;
import ctrs.bean.QueryInfo;
import ctrs.bean.User;
import ctrs.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;

@RestController
public class UserController {

    @Autowired
    UserDao userDao;

    @CrossOrigin
    @RequestMapping("/allUser")
    public String getUserList(QueryInfo queryInfo) {
        System.out.println(queryInfo);
        List<User> users = userDao.getAllUser("%" + queryInfo.getQuery() + "%");
        HashMap<String, Object> res = new HashMap<>();
        res.put("data", users);
        System.out.println("res:" + res);
        String users_json = JSON.toJSONString(res);
        return users_json;
    }

    @RequestMapping("/addUser")
    public String addUser(@RequestBody User user) {
        int i = userDao.addUser(user);
        return i > 0 ? "success" : "error";
    }

    @RequestMapping("/getUpdate")
    public String getUpdateUser(String userId) {
        System.out.println("编号:" + userId);
        User updateUser = userDao.getUpdateUser(userId);
        String users_json = JSON.toJSONString(updateUser);
        return users_json;
    }

    @RequestMapping("/editUser")
    public String editUser(@RequestBody User user) {
        System.out.println(user);
        int i = userDao.editUser(user);
        String str = i > 0 ? "success" : "error";
        return str;
    }

    @RequestMapping("/deleteUser")
    public String deleteUser(String userId) {
        System.out.println(userId);
        int i = userDao.deleteUser(userId);
        String str = i > 0 ? "success" : "error";
        return str;
    }
}
